package com.yanfan.ibms.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yanfan.common.constant.Constants;
import com.yanfan.common.utils.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 通用http发送方法
 *
 * @author ruoyi
 */
public class HttpUtils2 {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils2.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String url) {
        return sendGet(url, StringUtils.EMPTY);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String url, String param) {
        return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url         发送请求的 URL
     * @param param       请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String url, String param, String contentType) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return JSON.parseObject(result.toString());
    }

    /**
     * 忽略SLL
     * @param url
     * @param param
     * @param contentType
     * @return
     */
    public static JSONObject sendSSLGet(String url, String param) {
        StringBuilder result = new StringBuilder();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;

        try {
            // 创建一个信任所有证书的 SSL 上下文
            SSLContext sslContext = SSLContextBuilder.create()
                    .loadTrustMaterial((chain, authType) -> true)
                    .build();

            // 创建一个忽略主机名验证的 SSL 连接套接字工厂
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            // 创建 HttpClient
            httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();

            // 处理请求参数
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            HttpGet httpGet = new HttpGet(urlNameString);

            // 执行请求
            response = httpClient.execute(httpGet);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }

            log.info("recv - {}", result);

        } catch (Exception e) {
            log.error("调用sendGet Exception, url=" + url + ", param=" + param, e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception ex) {
                log.error("关闭 HttpClient Exception, url=" + url + ", param=" + param, ex);
            }
        }

        return JSON.parseObject(result.toString());
    }

    /**
     * 忽略SSl
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static JSONObject sendSLLGetParm(String url, Map<String, String> headers, Map<String, Object> params) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            // 构建请求参数字符串
            StringJoiner paramJoiner = new StringJoiner("&");
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    paramJoiner.add(entry.getKey() + "=" + entry.getValue());
                }
            }
            String urlNameString = paramJoiner.length() > 0 ? url + "?" + paramJoiner : url;
            log.info("sendGet - {}", urlNameString);

            // 忽略SSL证书验证
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true)
                    .build();

            // 使用HttpsURLConnection进行SSL连接
            HttpsURLConnection connection = (HttpsURLConnection) new URL(urlNameString).openConnection();
            connection.setSSLSocketFactory(sslContext.getSocketFactory());
            connection.setHostnameVerifier(NoopHostnameVerifier.INSTANCE);

            // 设置请求头
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            if (headers != null) {
                for (Map.Entry<String, String> header : headers.entrySet()) {
                    connection.setRequestProperty(header.getKey(), header.getValue());
                }
            }

            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), headers.getOrDefault("Content-Type", "UTF-8")));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch ( IOException e) {
            log.error("调用HttpUtils.sendGet Exception, url=" + url, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url, ex);
            }
        }
        return JSON.parseObject(result.toString());
    }
    /**
     * 向指定 URL 发送POST方法的请求  无请求头参数 表单形式 Content-Type,application/x-www-form-urlencoded
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数HashMap<String, Object> params的形式。
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPostNotHeader(String url, HashMap<String, Object> params) {
        String param = ParamUtils.toQueryParamString(params);
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return JSON.parseObject(result.toString());
    }

    /**
     * 向指定 URL 发送POST方法的请求 json格式  content-type", application/json;charset=UTF-8  有请求头
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数HashMap<String, Object> params的形式。
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPostBody(String url, Map<String, String> headers, HashMap<String, Object> params) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        ObjectMapper objectMapper = new ObjectMapper(); // 用于将 HashMap 转换为 JSON 字符串

        try {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置默认请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("content-type", "application/json;charset=UTF-8");

            // 如果有自定义请求头，则设置
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 将 HashMap 转换为 JSON 字符串
            String jsonParam = objectMapper.writeValueAsString(params);

            // 发送请求参数 (以 JSON 形式)
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
            out.print(jsonParam);
            out.flush();

            // 读取响应结果
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ", param=" + params, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ", param=" + params, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ", param=" + params, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ", param=" + params, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ", param=" + params, ex);
            }
        }

        return JSON.parseObject(result.toString());
    }

    /**
     * SSL
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static JSONObject sendPostSSLBody(String url, Map<String, String> headers, HashMap<String, Object> params) {
        StringBuilder result = new StringBuilder();
        ObjectMapper objectMapper = new ObjectMapper(); // 用于将 HashMap 转换为 JSON 字符串

        try {
            log.info("sendPost - {}", url);

            // 创建一个信任所有证书的 SSL 上下文
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true)
                    .build();

            // 创建一个忽略主机名验证的 SSL 连接套接字工厂
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            // 创建 HttpClient
            try (CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build()) {
                HttpPost httpPost = new HttpPost(url);

                // 设置默认请求头
                httpPost.setHeader("accept", "*/*");
                httpPost.setHeader("connection", "Keep-Alive");
                httpPost.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
                httpPost.setHeader("content-type", "application/json;charset=UTF-8");

                // 如果有自定义请求头，则设置
                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        httpPost.setHeader(entry.getKey(), entry.getValue());
                    }
                }

                // 将 HashMap 转换为 JSON 字符串
                String jsonParam = objectMapper.writeValueAsString(params);
                httpPost.setEntity(new StringEntity(jsonParam, StandardCharsets.UTF_8));

                // 执行请求并获取响应
                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
                    String line;
                    while ((line = in.readLine()) != null) {
                        result.append(line);
                    }
                    log.info("recv - {}", result);
                }
            }
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ", param=" + params, e);
        }

        return JSON.parseObject(result.toString());
    }


    /**
     * 向指定 URL 发送POST方法的请求 表单形式 Content-Type,application/x-www-form-urlencoded
     *
     * @param url     发送请求的 URL
     * @param params  请求参数，请求参数HashMap<String, Object>的形式。
     * @param headers 请求头参数，Map形式，可以为空
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPostForm(String url, Map<String, String> headers, HashMap<String, Object> params) {
        String param = ParamUtils.toQueryParamString(params);
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置默认请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");

            // 如果有自定义请求头，则设置
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 发送请求参数
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();

            // 读取响应结果
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return JSON.parseObject(result.toString());
    }

    public static JSONObject sendSSLPost(String url, String param) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !"".equals(ret.trim())) {
                    result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return JSON.parseObject(result.toString());
    }


    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}
